package com.fit4as.fit
{
import mx.utils.StringUtil;


    // Copyright (c) 2002 Cunningham & Cunningham, Inc.
    // Released under the terms of the GNU General Public License version 2 or later.

    // Warning: not (yet) a general number usable in all calculations.

public class ScientificDouble implements Comparable {

    protected var value : Number;
    protected var precision : Number;

    public function ScientificDouble(value : Number) {
        this.value = value;
        this.precision = 0;
    }

    public static function valueOf(s : String) : ScientificDouble {
        var result : ScientificDouble = new ScientificDouble(parseFloat(s));
        result.precision = precision(s);
        return result;
    }

    public static function precision(s : String) : Number {
        var value : Number = parseFloat(s);
        var bound : Number = parseFloat(tweak(StringUtil.trim(s)));
        return Math.abs(bound - value);
    }

    public static function tweak(s : String) : String {
        var pos : int;
        if ((pos = s.toLowerCase().indexOf("e")) >= 0) {
            return tweak(s.substring(0, pos)) + s.substring(pos);
        }
        if (s.indexOf(".") >= 0) {
            return s + "5";
        }
        return s + ".5";
    }



    public function equals(obj : Object) : Boolean {
        return compareTo(obj) == 0;
    }

    public function compareTo(obj : Object) : int {
        var other : Number = Number(obj);
        var diff : Number = value - other;
        // System.out.println(value+" "+precision+" "+diff);
        if (diff < -precision) return -1;
        if (diff > precision) return 1;
        if (isNaN(value) && isNaN(other)) return 0;
        if (isNaN(value)) return 1;
        if (isNaN(other)) return -1;
        return 0;
    }

    public function toString() : String {
        return value.toString();
    }

    public function doubleValue() : Number {
        return value;
    }

    public function floatValue() : Number {
        return value;
    }

    public function longValue() : int {
        return int(value);
    }

    public function intValue() : int {
        return int(value);
    }
}
}